package handler

import (
	"strconv"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"

	"yanxue_ai_go/pkg/common/logger"
	"yanxue_ai_go/pkg/common/response"
	"yanxue_ai_go/services/rag/internal/service"
)

// RAGHandler RAG处理器
type RAGHandler struct {
	ragService *service.RAGService
}

// NewRAGHandler 创建RAG处理器
func NewRAGHandler(ragService *service.RAGService) *RAGHandler {
	return &RAGHandler{
		ragService: ragService,
	}
}

// CreateKnowledgeBase 创建知识库
func (h *RAGHandler) CreateKnowledgeBase(c *gin.Context) {
	var req service.CreateKnowledgeBaseRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	kb, err := h.ragService.CreateKnowledgeBase(c.Request.Context(), &req)
	if err != nil {
		logger.Logger.Error("Failed to create knowledge base", zap.Error(err))
		response.InternalServerError(c, "Failed to create knowledge base")
		return
	}

	response.Success(c, kb)
}

// GetKnowledgeBase 获取知识库详情
func (h *RAGHandler) GetKnowledgeBase(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		response.BadRequest(c, "Invalid knowledge base ID")
		return
	}

	kb, err := h.ragService.GetKnowledgeBase(c.Request.Context(), uint(id))
	if err != nil {
		response.NotFound(c, "Knowledge base not found")
		return
	}

	response.Success(c, kb)
}

// ListKnowledgeBases 获取知识库列表
func (h *RAGHandler) ListKnowledgeBases(c *gin.Context) {
	var req service.ListKnowledgeBasesRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	// 设置默认值
	if req.Page == 0 {
		req.Page = 1
	}
	if req.PageSize == 0 {
		req.PageSize = 10
	}

	kbs, total, err := h.ragService.ListKnowledgeBases(c.Request.Context(), &req)
	if err != nil {
		logger.Logger.Error("Failed to list knowledge bases", zap.Error(err))
		response.InternalServerError(c, "Failed to list knowledge bases")
		return
	}

	response.Success(c, gin.H{
		"knowledge_bases": kbs,
		"total":           total,
		"page":            req.Page,
		"page_size":       req.PageSize,
	})
}

// UpdateKnowledgeBase 更新知识库
func (h *RAGHandler) UpdateKnowledgeBase(c *gin.Context) {
	// TODO: 实现更新逻辑
	response.Success(c, gin.H{"message": "Knowledge base update not implemented yet"})
}

// DeleteKnowledgeBase 删除知识库
func (h *RAGHandler) DeleteKnowledgeBase(c *gin.Context) {
	// TODO: 实现删除逻辑
	response.Success(c, gin.H{"message": "Knowledge base deletion not implemented yet"})
}

// CreateDocument 创建文档
func (h *RAGHandler) CreateDocument(c *gin.Context) {
	var req service.CreateDocumentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	doc, err := h.ragService.CreateDocument(c.Request.Context(), &req)
	if err != nil {
		logger.Logger.Error("Failed to create document", zap.Error(err))
		response.InternalServerError(c, "Failed to create document")
		return
	}

	response.Success(c, doc)
}

// ListDocuments 获取文档列表
func (h *RAGHandler) ListDocuments(c *gin.Context) {
	// TODO: 实现文档列表逻辑
	response.Success(c, gin.H{"message": "Document listing not implemented yet"})
}

// GetDocument 获取文档详情
func (h *RAGHandler) GetDocument(c *gin.Context) {
	// TODO: 实现文档详情逻辑
	response.Success(c, gin.H{"message": "Document details not implemented yet"})
}

// UpdateDocument 更新文档
func (h *RAGHandler) UpdateDocument(c *gin.Context) {
	// TODO: 实现文档更新逻辑
	response.Success(c, gin.H{"message": "Document update not implemented yet"})
}

// DeleteDocument 删除文档
func (h *RAGHandler) DeleteDocument(c *gin.Context) {
	// TODO: 实现文档删除逻辑
	response.Success(c, gin.H{"message": "Document deletion not implemented yet"})
}

// ChunkDocument 文档分块
func (h *RAGHandler) ChunkDocument(c *gin.Context) {
	// TODO: 实现文档分块逻辑
	response.Success(c, gin.H{"message": "Document chunking not implemented yet"})
}

// SemanticSearch 语义搜索
func (h *RAGHandler) SemanticSearch(c *gin.Context) {
	var req service.SearchRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	results, err := h.ragService.SemanticSearch(c.Request.Context(), &req)
	if err != nil {
		logger.Logger.Error("Failed to perform semantic search", zap.Error(err))
		response.InternalServerError(c, "Failed to perform search")
		return
	}

	response.Success(c, results)
}

// HybridSearch 混合搜索
func (h *RAGHandler) HybridSearch(c *gin.Context) {
	var req service.SearchRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	results, err := h.ragService.HybridSearch(c.Request.Context(), &req)
	if err != nil {
		logger.Logger.Error("Failed to perform hybrid search", zap.Error(err))
		response.InternalServerError(c, "Failed to perform search")
		return
	}

	response.Success(c, results)
}

// SimilaritySearch 相似性搜索
func (h *RAGHandler) SimilaritySearch(c *gin.Context) {
	// TODO: 实现相似性搜索逻辑
	response.Success(c, gin.H{"message": "Similarity search not implemented yet"})
}

// AskQuestion 问答
func (h *RAGHandler) AskQuestion(c *gin.Context) {
	var req service.QARequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	answer, err := h.ragService.AskQuestion(c.Request.Context(), &req)
	if err != nil {
		logger.Logger.Error("Failed to answer question", zap.Error(err))
		response.InternalServerError(c, "Failed to answer question")
		return
	}

	response.Success(c, answer)
}

// ChatWithKnowledge 知识问答对话
func (h *RAGHandler) ChatWithKnowledge(c *gin.Context) {
	var req service.ChatRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	chatResp, err := h.ragService.ChatWithKnowledge(c.Request.Context(), &req)
	if err != nil {
		logger.Logger.Error("Failed to chat with knowledge", zap.Error(err))
		response.InternalServerError(c, "Failed to chat")
		return
	}

	response.Success(c, chatResp)
}

// GetChatHistory 获取聊天历史
func (h *RAGHandler) GetChatHistory(c *gin.Context) {
	// TODO: 实现聊天历史逻辑
	response.Success(c, gin.H{"message": "Chat history not implemented yet"})
}

// EmbedText 文本向量化
func (h *RAGHandler) EmbedText(c *gin.Context) {
	// TODO: 实现文本向量化逻辑
	response.Success(c, gin.H{"message": "Text embedding not implemented yet"})
}

// BatchEmbed 批量向量化
func (h *RAGHandler) BatchEmbed(c *gin.Context) {
	// TODO: 实现批量向量化逻辑
	response.Success(c, gin.H{"message": "Batch embedding not implemented yet"})
}
